package com.automailerbot.captcha;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

public class CaptchaSolver2Captcha {

    private final String apiKey;

    public CaptchaSolver2Captcha(String apiKey) {
        this.apiKey = apiKey;
    }

    public String solveReCaptcha(String siteKey, String pageUrl) throws Exception {
        String requestUrl = String.format(
                "http://2captcha.com/in.php?key=%s&method=userrecaptcha&googlekey=%s&pageurl=%s",
                apiKey, siteKey, pageUrl
        );

        String response = sendGetRequest(requestUrl);
        if (!response.startsWith("OK|")) {
            throw new Exception("2Captcha 提交失败: " + response);
        }

        String requestId = response.split("\\|")[1];

        // 轮询获取结果
        for (int i = 0; i < 24; i++) {
            TimeUnit.SECONDS.sleep(5);
            String result = sendGetRequest(
                    "http://2captcha.com/res.php?key=" + apiKey + "&action=get&id=" + requestId
            );
            if (result.startsWith("OK|")) {
                return result.split("\\|")[1];
            } else if (!result.equals("CAPCHA_NOT_READY")) {
                throw new Exception("验证码识别失败: " + result);
            }
        }

        throw new Exception("验证码超时未获取成功");
    }

    private String sendGetRequest(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            return in.readLine();
        }
    }
}
